package com.yunquan.ohana.ui.history.details.adapter

import android.annotation.SuppressLint
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.listener.VideoAllCallBack
import com.yunquan.ohana.R
import com.yunquan.ohana.entity.LocalFileEntity
import com.yunquan.ohana.utils.GlideApp
import com.yunquan.ohana.utils.StringUtils
import com.yunquan.ohana.utils.ToastUtils
import com.yunquan.ohana.view.SampleCoverVideo
import java.io.File
import java.text.SimpleDateFormat
import java.util.Locale


class DetailsPagerAdapter(val photos: List<LocalFileEntity>) : RecyclerView.Adapter<DetailsPagerAdapter.ViewHolder>() {
    private var mListener: ((Int) -> Unit)? = null

    fun setOnItemClickListener(listener: (Int) -> Unit) {
        mListener = listener
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DetailsPagerAdapter.ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_details_header, parent, false)
        return ViewHolder(view)
    }

    override fun getItemCount(): Int {
        return photos.size
    }

    override fun onBindViewHolder(holder: DetailsPagerAdapter.ViewHolder, position: Int) {
        val item = photos[position]
        holder.bind(position, item)
    }


    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val videoContent: SampleCoverVideo = itemView.findViewById(R.id.video_content)
        private val imageContent: ImageView = itemView.findViewById(R.id.image_content)
        private val picLoading: ProgressBar = itemView.findViewById(R.id.pic_loading)
        private val layoutInfo: ConstraintLayout = itemView.findViewById(R.id.cl_info)
        private val tvContent: TextView = itemView.findViewById(R.id.tv_content)
        private val tvDate: TextView = itemView.findViewById(R.id.tv_date)
        private val ivState: ImageView = itemView.findViewById(R.id.iv_state)
        private val tvState: TextView = itemView.findViewById(R.id.tv_state)

        fun bind(position: Int, item: LocalFileEntity) {
            setCaption(item)
            if (item.type == 1) {
                setImageView(position, item)
            } else {
                setVideoView(position, item)
            }
        }

        private fun setImageView(position: Int, item: LocalFileEntity) {
            videoContent.visibility = View.GONE
            imageContent.visibility = View.VISIBLE
            picLoading.visibility = View.VISIBLE
            var path: String? = null
            var file: File? = null
            if (item.localCropPath != null) {
                file = File(item.localCropPath)
                if (!file.exists() && item.localFilePath != null) {
                    file = File(item.localFilePath)
                }
            } else if (item.localFilePath != null) {
                file = File(item.localFilePath)
            } else {
                path = item.fileUrl
            }
            val glide = if (path != null) {
                GlideApp.with(itemView.context).load(path)
            } else if (file?.exists() == true) {
                GlideApp.with(itemView.context).load(file)
            } else {
                GlideApp.with(itemView.context).load(R.mipmap.ic_default_image)
            }
            glide.override(800, 600)
                .transition(DrawableTransitionOptions.withCrossFade())
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .skipMemoryCache(false)
                .error(R.mipmap.ic_default_image)
                .listener(object : RequestListener<Drawable> {
                    override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>, isFirstResource: Boolean): Boolean {
                        picLoading.visibility = View.GONE
                        return false
                    }

                    override fun onResourceReady(
                        resource: Drawable,
                        model: Any,
                        target: Target<Drawable>?,
                        dataSource: DataSource,
                        isFirstResource: Boolean
                    ): Boolean {
                        picLoading.visibility = View.GONE
                        return false
                    }
                })
                .into(imageContent)

            imageContent.setOnClickListener {
                mListener?.invoke(position)
            }
        }

        private fun setVideoView(position: Int, item: LocalFileEntity) {
            videoContent.visibility = View.VISIBLE
            imageContent.visibility = View.GONE
            picLoading.visibility = View.GONE
            // 背景图
            val thumbnailPath = item.thumbnail ?: item.videoImgUrl
            if (!StringUtils.isEmpty(thumbnailPath)) {
                val thumbImageView = ImageView(itemView.context)
                if (thumbnailPath!!.startsWith("http")) {
                    GlideApp.with(itemView.context)
                        .load(thumbnailPath)
                        .override(800, 600)
                        .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                        .skipMemoryCache(false)
                        .into(thumbImageView)
                } else {
                    val file = File(thumbnailPath)
                    if (file.exists()) {
                        GlideApp.with(itemView.context)
                            .load(file)
                            .override(800, 600)
                            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                            .skipMemoryCache(false)
                            .into(thumbImageView)
                    }
                }
                videoContent.thumbImageView = thumbImageView
            }
            // 播放视频
            val videoPath = item.localCropPath ?: item.localFilePath ?: item.fileUrl
            val builder = GSYVideoOptionBuilder()
            builder.setUrl(videoPath)
                .setCacheWithPlay(false)
                .setLooping(false)
                .setAutoFullWithSize(false)
                .setShowFullAnimation(true)
                .setReleaseWhenLossAudio(false)
                .setThumbPlay(true)
                .setNeedLockFull(true)
                .setIsTouchWigetFull(true)
                .setIsTouchWiget(true)
                .setHideKey(false)
                .build(videoContent)
            videoContent.setOnClickListener {
                ToastUtils.showShort("点击了")
            }
            videoContent.titleTextView.visibility = View.GONE
            videoContent.backButton.visibility = View.GONE
            videoContent.fullscreenButton.visibility = View.GONE
            videoContent.setVideoAllCallBack(object : VideoAllCallBack {

                override fun onPrepared(url: String?, vararg objects: Any?) {
                    layoutInfo.visibility = View.GONE
                }

                override fun onAutoComplete(url: String?, vararg objects: Any?) {
                    layoutInfo.visibility = View.VISIBLE
                }

                override fun onPlayError(url: String?, vararg objects: Any?) {
                    layoutInfo.visibility = View.VISIBLE
                }

                override fun onClickStop(url: String?, vararg objects: Any?) {
                    layoutInfo.visibility = View.VISIBLE
                }

                override fun onStartPrepared(url: String?, vararg objects: Any?) {}

                override fun onClickStartIcon(url: String?, vararg objects: Any?) {
                    layoutInfo.visibility = View.GONE
                }

                override fun onClickStartError(url: String?, vararg objects: Any?) {
                    layoutInfo.visibility = View.VISIBLE
                }

                override fun onClickStopFullscreen(url: String?, vararg objects: Any?) {
                    layoutInfo.visibility = View.VISIBLE
                }

                override fun onClickResume(url: String?, vararg objects: Any?) {
                    layoutInfo.visibility = View.GONE
                }

                override fun onClickResumeFullscreen(url: String?, vararg objects: Any?) {
                    layoutInfo.visibility = View.GONE
                }

                override fun onClickSeekbar(url: String?, vararg objects: Any?) {}

                override fun onClickSeekbarFullscreen(url: String?, vararg objects: Any?) {}

                override fun onComplete(url: String?, vararg objects: Any?) {}

                override fun onEnterFullscreen(url: String?, vararg objects: Any?) {}

                override fun onQuitFullscreen(url: String?, vararg objects: Any?) {}

                override fun onQuitSmallWidget(url: String?, vararg objects: Any?) {}

                override fun onEnterSmallWidget(url: String?, vararg objects: Any?) {}

                override fun onTouchScreenSeekVolume(url: String?, vararg objects: Any?) {}

                override fun onTouchScreenSeekPosition(url: String?, vararg objects: Any?) {}

                override fun onTouchScreenSeekLight(url: String?, vararg objects: Any?) {}

                override fun onClickStartThumb(url: String?, vararg objects: Any?) {}

                override fun onClickBlank(url: String?, vararg objects: Any?) {}

                override fun onClickBlankFullscreen(url: String?, vararg objects: Any?) {}

            })
            videoContent.startPlayLogic()
        }

        @SuppressLint("SetTextI18n")
        private fun setCaption(item: LocalFileEntity) {
            tvContent.text = item.content
            val format = SimpleDateFormat("dd MMMM yyyy", Locale.ENGLISH)
            tvDate.text = format.format(item.createTime)
            when (item.status) {
                1 -> {
                    ivState.visibility = View.VISIBLE
                    tvState.visibility = View.VISIBLE
                    ivState.setImageResource(R.mipmap.ic_details_completed)
                    tvState.text = "Completed"
                }

                2 -> {
                    ivState.visibility = View.VISIBLE
                    tvState.visibility = View.VISIBLE
                    ivState.setImageResource(R.mipmap.ic_details_failed)
                    tvState.text = "Failed"
                }

                else -> {
                    ivState.visibility = View.INVISIBLE
                    tvState.visibility = View.INVISIBLE
                }
            }
        }
    }
}